package com.wx.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.jfinal.plugin.activerecord.Db;
import com.wx.model.PartyGetBonusRecord;
import com.wx.model.PartyInfo;
import com.wx.model.PartyLotteryNum;
import com.wx.model.PartyPrizeDetail;
import com.wx.model.PartyPrizeGroup;
import com.wx.model.PartyPrizeRecord;
import com.wx.model.PartyPrizeSummary;
import com.wx.model.PartyRule;
import com.wx.model.PartyTicket;
import com.wx.model.PartyTicketDetail;
import com.wx.model.PartyUser;
import com.wx.model.PartyUserSerinfo;
import com.wx.sql.MarketingSql;
import com.wx.util.DrawLotteryUtil;
import com.wx.util.Gift;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.NumberUtil;

/**
 * ClassName: MarketingService 
 * @Description:营销类接口实现类
 * @author liuxin
 * @date 2018年5月17日
 */
public class MarketingService { 
	public static final MarketingService me = new MarketingService();
	private final PartyUser userDao = new PartyUser().dao();
	private final PartyRule ruleDao = new PartyRule().dao();
	private final PartyLotteryNum lotteryNumDao = new PartyLotteryNum().dao();
	private final PartyUserSerinfo userSerinfoDao = new PartyUserSerinfo().dao();
	private final PartyInfo partyInfoDao = new PartyInfo().dao();
	private final PartyPrizeGroup partyPrizeGroupDao = new PartyPrizeGroup().dao();
	private final PartyPrizeDetail partyPrizeDetailDao = new PartyPrizeDetail();
	private final PartyTicket ticketDao = new PartyTicket();
	//private final PartyTicketDetail ticketDetailDao = new PartyTicketDetail();
	private final PartyPrizeSummary prizeSummaryDao = new PartyPrizeSummary();
	//private final PartyPrizeRecord prizeRecordDao = new PartyPrizeRecord();
	//private final PartyGetBonusRecord getBonusRecordDao = new PartyGetBonusRecord();
	/**
	 * @Description: 获得奖励次数
	 * @param @param map:
	 * {
	 * 	USER_CODE:"1001",用户编码
	 *  USER_SOURCE:"0",(0:江津，1:常州),
	 *  USER_TYPE:"1001",用户类型
	 *  LOGIN_NUM："2",签到次数
	 *  ORDER_NUM："2",下单次数
	 *  REPEAT_NUM："2",转发次数
	 *  PARTY_ID:"1001"活动ID
	 * }
	 * @param @return   
	 * @return Map<String,Object>  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public Easy getNumberOfAwards(Map<String, Object> map) {
		Easy easy = new Easy();

		//根据用户编码和用户来源以及用户类型判断用户是否存在
		List<PartyUser> userList = userDao.find(MarketingSql.getUserString(map));
		if(userList.size() > 0){

			PartyUser user = userList.get(0);

			//根据活动规则获取该用户此次应当获得的奖励次数
			List<PartyRule> ruleList = ruleDao.find(MarketingSql.getRuleString(map));

			if(ruleList.size() > 0){

				map.put("USER_ID", user.getId());
				//更新用户信息拉取表
				updateUserSerInfo(map);

				PartyRule rule = ruleList.get(0);

				//更新 用户资源表
				Map<String, Object> reuMap = updateLotteryNum(map,rule);
				PartyLotteryNum lotteryNum = (PartyLotteryNum) reuMap.get("partyLotteryNum");
				//
				PartyGetBonusRecord bonusRecord = new PartyGetBonusRecord();
				bonusRecord.setUserId(user.getId());
				bonusRecord.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
				bonusRecord.setPrizeNum(Integer.parseInt(reuMap.get("lotteryNum").toString()));
				bonusRecord.save();

				easy.setSuccess(true);
				easy.setMsg("SUCCESS");
				easy.setData(lotteryNum);

			}else{
				easy.setSuccess(true);
				easy.setMsg("请先根据来源和活动ID维护活动规则");
			}
		}else{
			easy.setSuccess(true);
			easy.setMsg("该用户不存在，请检查其编码和用户来源以及用户类型是否一致");
		}
		return easy;
	}

	/**
	 * @Description: 获取用户所得奖励
	 * @param @param map
	 * {
	 * USER_CODE:"1001",用户编码，
	 * PARTY_ID:"1001"活动ID
	 * }
	 * @param @return   
	 * @return Easy  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月18日
	 */
	public Easy getAReward(Map<String, Object> map){
		Easy easy = new Easy();
		//根据活动类型判断是需要积分 还是需要次数
		PartyInfo partyInfo = partyInfoDao.findById(map.get("PARTY_ID"));
		int reduceType = partyInfo.getReduceType();
		boolean flag = false;
		String errmsg = "";
		PartyUser user = userDao.findFirst("select * from party_user where user_code = '"+map.get("USER_CODE")+"'");
		int score = 0;
		if(reduceType == 0 ){
			//抽奖次数
			List<PartyLotteryNum> lotteryNumList = lotteryNumDao.find(MarketingSql.getLotteryNum(map));
			PartyLotteryNum	partyLotteryNum = lotteryNumList.get(0);
			if(partyLotteryNum.getLotteryNum() > 0){
				//用户资源表
				if(partyLotteryNum.getLotteryNum()>=1){
					partyLotteryNum.setLotteryNum(partyLotteryNum.getLotteryNum() - 1);
					partyLotteryNum.setUpdateDate(new Date());
					partyLotteryNum.update();
					flag = true;
				}else{
					flag = false;
					errmsg = "用户抽奖机会不足";
				}
			}else{
				flag = false;
				errmsg = "用户还没得到抽奖机会";
			}
		}else{
			//积分抽奖
			Map paramMap=new HashMap<>();
			paramMap.put("key", user.getRequestKey());
			paramMap.put("points", partyInfo.getReduceNum());
			//获取请求URL
			String actionUrl = xx.getConfig(user.getUserSource()+"URL")+"api.php?controller=jackpot&action=changeOpportunityForLottery";
			String response = HttpUtil.get(actionUrl, paramMap);
			System.out.println("======="+response);
			Map parammap = JSONUtil.parseObj(response);
			if(parammap.get("errcode")!=null&&(int)parammap.get("errcode")==0){
				//获得积分
				score = (int) ((Map)parammap.get("info")).get("month_score");
				flag = true;
			}else{
				score = 0;
				flag = false;
				errmsg = "积分不够，不能抽奖";
			}
		}
        if(flag){
			Date now = new Date();
			if(now.after(partyInfo.getEndTime())){
				easy.setMsg("活动已经结束了哦！");
				easy.setSuccess(true);
			}else if(now.before(partyInfo.getStartTime())){
				easy.setMsg("活动还没开始哦！");
				easy.setSuccess(true);
			}else{
				PartyPrizeGroup prizeGroup = partyPrizeGroupDao.findFirst(MarketingSql.getPrizeGroup(map));
				//获取奖励明细()
				List<PartyPrizeDetail>  prizeDetailList = partyPrizeDetailDao.find(MarketingSql.getPrizeDetail(prizeGroup.getId()));
				//最终参与抽奖的奖励明细（排除没有达到阀值的和奖励商品券剩余数量为0 的）
				List<PartyPrizeDetail> partyPrizeDetailList = new ArrayList<PartyPrizeDetail>() ;
				//总概率
				int sum = 0;
				for(PartyPrizeDetail prizeDetail :prizeDetailList ){
					//获取奖励券（判断奖励券是否有剩余）
					PartyTicket ticket = ticketDao.findFirst(MarketingSql.getTicket(prizeDetail.getTicketId()));
					//总的参与人数
					int party_num = 0;
					//该奖项已发个数 
					int prize_num = 0;
					List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(prizeDetail.getId()));
					if(prizeSummarieList.size() > 0){
						prize_num = prizeSummarieList.get(0).getPrizeNum();
					}
					//个人 、总体 （判断阀值）
					if(prizeDetail.getThresholdType() == 0){
						party_num = Db.queryInt("SELECT COUNT(ID) FROM party_prize_record WHERE party_id = "+map.get("PARTY_ID")+" AND user_id = "+user.getId()+"" );
					}else{
						party_num = Db.queryInt("SELECT IFNULL(SUM( IFNULL( prize_num, 0 )),0) FROM party_prize_summary WHERE party_id = "+map.get("PARTY_ID")+"") ;
					}
					//阀值计算方式：（奖励已发次数+1） * 下线阀值系数
					if(party_num >= (prize_num+1) * prizeDetail.getThreshold()){
						if(ticket != null && ticket.getResidualQuantity() > 0){
							partyPrizeDetailList.add(prizeDetail);
							sum += prizeDetail.getPrizeProbability();
						}
					}
				}
				if(sum != 0 ){
					//kai shi chou jiang
					Random random = new Random();  
					//sui ji chan sheng zhong jiang hao ma ,pan duan gai hao hao ma chu yu na ge duan 
					int num = random.nextInt(sum); 
					int total = 0;
					int preNum = 0;
					PartyPrizeDetail reward = null ;
//						for(PartyPrizeDetail prizeDetail :partyPrizeDetailList){
					 List<Gift> list = new ArrayList<Gift>();
					for(int i=0;i<partyPrizeDetailList.size();i++){	
						  Gift iphone = new Gift();
					      iphone.setId(i);
					      iphone.setName(partyPrizeDetailList.get(i).getPrizeName());
					      Double dd =NumberUtil.div(partyPrizeDetailList.get(i).getPrizeProbability()+0.00, sum+0.00, 2);
					      iphone.setProb(dd);
					      list.add(iphone);
					}
					int index = DrawLotteryUtil.drawGift(list);
					reward = partyPrizeDetailList.get(index);
					if(reduceType == 0 ){
						reward.setGroupId(1);
					}else{
						reward.setGroupId(score);
					}
//						for(PartyPrizeDetail prizeDetail :partyPrizeDetailList){
//							total += prizeDetail.getPrizeProbability();
//							if(num >= preNum && num <total){
//								reward = prizeDetail;
//								break;
//							}
//							preNum += prizeDetail.getPrizeProbability();
//						}

					//==========================geng xin biao xin xi================================//
					PartyTicket ticket = new PartyTicket();
					
					//分配商品券
					PartyTicketDetail partyTicketDetail =  new PartyTicketDetail();
					ticket = ticket.findFirst(MarketingSql.getTicket(reward.getTicketId()));
					String tmm_ticket_code = getRewardFormTMM(user,ticket.getRequestKey());
					if(!"".equals(tmm_ticket_code)&&!"ERR".equals(tmm_ticket_code)){
						//第三方生成
						if(ticket.getCreateType() == 3){
							partyTicketDetail.setTicketId(reward.getTicketId());
							partyTicketDetail.setLotteryTime(new Date());
							partyTicketDetail.setTmmTicketCode(tmm_ticket_code);
							partyTicketDetail.setTicketStatus(1);
							partyTicketDetail.setUserId(user.getId());
							partyTicketDetail.setUpdateDate(new Date());
							partyTicketDetail.setCreateDate(new Date());
							partyTicketDetail.setPrizeDetailId(reward.getId());
							partyTicketDetail.save();
						}else{
							//导入
							synchronized (MarketingService.class) {
								List<PartyTicketDetail> partyTicketDetails = partyTicketDetail.dao().find("SELECT * FROM party_ticket_detail ptd WHERE ticket_id =? AND ticket_status = ? LIMIT  1,1",reward.getTicketId(),0);
								if(partyTicketDetails.size() > 0){
									partyTicketDetail = partyTicketDetails.get(0);
									partyTicketDetail.setLotteryTime(new Date());
									partyTicketDetail.setTmmTicketCode(tmm_ticket_code);
									partyTicketDetail.setTicketStatus(1);
									partyTicketDetail.setUserId(user.getId());
									partyTicketDetail.setUpdateDate(new Date());
									partyTicketDetail.setPrizeDetailId(reward.getId());
									partyTicketDetail.update();
								}else{
									easy.setMsg("您抽中的奖品已经发送完毕，请下次努力哦！");
									easy.setSuccess(true);
									return easy;
								}
							}
						}
					}else{
						easy.setMsg("您抽中的奖品已经发送完毕，请下次努力哦！");
						easy.setSuccess(true);
						easy.setData(reward);
						return easy;
					}
					
					//奖励商品券
					if(Db.update(MarketingSql.updateTicket(reward.getTicketId())) == 1){
						//商品奖励信息汇总表
						PartyPrizeSummary prizeSummary  ;
						List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(reward.getId()));
						if(prizeSummarieList.size() > 0){
							prizeSummary  = prizeSummarieList.get(0);
							prizeSummary.setPrizeNum(prizeSummary.getPrizeNum() + 1 );
							prizeSummary.setUpdateDate(new Date());
							prizeSummary.update();
						}else{
							prizeSummary = new PartyPrizeSummary();
							prizeSummary.setPrizeNum(1);
							prizeSummary.setPrizeId(reward.getId());
							prizeSummary.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
							prizeSummary.save();
						}
						//参与活动明细表
						PartyPrizeRecord prizeRecord = new PartyPrizeRecord();
						prizeRecord.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
						prizeRecord.setPrizeId(reward.getId());
						prizeRecord.setPrizeName(reward.getPrizeName());
						prizeRecord.setUserId(user.getId());
						prizeRecord.setParticipationTime(new Date());
						prizeRecord.save();
						//确定抽奖
						easy.setData(reward);
						easy.setMsg("SUCCESS");
						easy.setSuccess(true);
					}else {
						easy.setMsg("您抽中的奖品已经发送完毕，请下次努力将哦！");
						easy.setSuccess(true);
					}
				}else{
					easy.setMsg("奖励已经发完，下次请早！");
					easy.setSuccess(true);
				}
			}
		
	    }else{
			easy.setMsg(errmsg);
			easy.setSuccess(true);
		}
        
		return easy;
//		List<PartyLotteryNum> lotteryNumList = lotteryNumDao.find(MarketingSql.getLotteryNum(map));
//		if(lotteryNumList.size() > 0){
//			PartyLotteryNum	partyLotteryNum = lotteryNumList.get(0);
//			if(partyLotteryNum.getLotteryNum() > 0){
//				//用户资源表
//				partyLotteryNum.setLotteryNum(partyLotteryNum.getLotteryNum() - 1);
//				partyLotteryNum.setUpdateDate(new Date());
//				partyLotteryNum.update();
//				PartyInfo partyInfo = partyInfoDao.findById(map.get("PARTY_ID"));
//				Date now = new Date();
//				if(now.after(partyInfo.getEndTime())){
//					easy.setMsg("活动已经结束了哦！");
//					easy.setSuccess(true);
//				}else if(now.before(partyInfo.getStartTime())){
//					easy.setMsg("活动还没开始哦！");
//					easy.setSuccess(true);
//				}else{
//					PartyUser user = userDao.findFirst("select * from party_user where user_code = '"+map.get("USER_CODE")+"'");
//				
//					PartyPrizeGroup prizeGroup = partyPrizeGroupDao.findFirst(MarketingSql.getPrizeGroup(map));
//					//获取奖励明细()
//					List<PartyPrizeDetail>  prizeDetailList = partyPrizeDetailDao.find(MarketingSql.getPrizeDetail(prizeGroup.getId()));
//					//最终参与抽奖的奖励明细（排除没有达到阀值的和奖励商品券剩余数量为0 的）
//					List<PartyPrizeDetail> partyPrizeDetailList = new ArrayList<PartyPrizeDetail>() ;
//					//总概率
//					int sum = 0;
//					for(PartyPrizeDetail prizeDetail :prizeDetailList ){
//						//获取奖励券（判断奖励券是否有剩余）
//						PartyTicket ticket = ticketDao.findFirst(MarketingSql.getTicket(prizeDetail.getTicketId()));
//						//总的参与人数
//						int party_num = 0;
//						//该奖项已发个数 
//						int prize_num = 0;
//						List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(prizeDetail.getId()));
//						if(prizeSummarieList.size() > 0){
//							prize_num = prizeSummarieList.get(0).getPrizeNum();
//						}
//						//个人 、总体 （判断阀值）
//						if(prizeDetail.getThresholdType() == 0){
//							party_num = Db.queryInt("SELECT COUNT(ID) FROM party_prize_record WHERE party_id = "+map.get("PARTY_ID")+" AND user_id = "+user.getId()+"" );
//						}else{
//							party_num = Db.queryInt("SELECT IFNULL(SUM( IFNULL( prize_num, 0 )),0) FROM party_prize_summary WHERE party_id = "+map.get("PARTY_ID")+"") ;
//						}
//						//阀值计算方式：（奖励已发次数+1） * 下线阀值系数
//						if(party_num >= (prize_num+1) * prizeDetail.getThreshold()){
//							if(ticket != null && ticket.getResidualQuantity() > 0){
//								partyPrizeDetailList.add(prizeDetail);
//								sum += prizeDetail.getPrizeProbability();
//							}
//						}
//					}
//					if(sum != 0 ){
//						//kai shi chou jiang
//						Random random = new Random();  
//						//sui ji chan sheng zhong jiang hao ma ,pan duan gai hao hao ma chu yu na ge duan 
//						int num = random.nextInt(sum); 
//						int total = 0;
//						int preNum = 0;
//						PartyPrizeDetail reward = null ;
////						for(PartyPrizeDetail prizeDetail :partyPrizeDetailList){
//						 List<Gift> list = new ArrayList<Gift>();
//						for(int i=0;i<partyPrizeDetailList.size();i++){	
//							  Gift iphone = new Gift();
//						      iphone.setId(i);
//						      iphone.setName(partyPrizeDetailList.get(i).getPrizeName());
//						      Double dd =NumberUtil.div(partyPrizeDetailList.get(i).getPrizeProbability()+0.00, sum+0.00, 2);
//						      iphone.setProb(dd);
//						      list.add(iphone);
//						}
//						int index = DrawLotteryUtil.drawGift(list);
//						reward = partyPrizeDetailList.get(index);
////						for(PartyPrizeDetail prizeDetail :partyPrizeDetailList){
////							total += prizeDetail.getPrizeProbability();
////							if(num >= preNum && num <total){
////								reward = prizeDetail;
////								break;
////							}
////							preNum += prizeDetail.getPrizeProbability();
////						}
//
//						//==========================geng xin biao xin xi================================//
//						PartyTicket ticket = new PartyTicket();
//						
//						//分配商品券
//						PartyTicketDetail partyTicketDetail =  new PartyTicketDetail();
//						ticket = ticket.findFirst(MarketingSql.getTicket(reward.getTicketId()));
//						String tmm_ticket_code = getRewardFormTMM(user,ticket.getRequestKey());
//						if(!"".equals(tmm_ticket_code)&&!"ERR".equals(tmm_ticket_code)){
//							//第三方生成
//							if(ticket.getCreateType() == 3){
//								partyTicketDetail.setTicketId(reward.getTicketId());
//								partyTicketDetail.setLotteryTime(new Date());
//								partyTicketDetail.setTmmTicketCode(tmm_ticket_code);
//								partyTicketDetail.setTicketStatus(1);
//								partyTicketDetail.setUserId(user.getId());
//								partyTicketDetail.setUpdateDate(new Date());
//								partyTicketDetail.setCreateDate(new Date());
//								partyTicketDetail.setPrizeDetailId(reward.getId());
//								partyTicketDetail.save();
//							}else{
//								//导入
//								synchronized (MarketingService.class) {
//									List<PartyTicketDetail> partyTicketDetails = partyTicketDetail.dao().find("SELECT * FROM party_ticket_detail ptd WHERE ticket_id =? AND ticket_status = ? LIMIT  1,1",reward.getTicketId(),0);
//									if(partyTicketDetails.size() > 0){
//										partyTicketDetail = partyTicketDetails.get(0);
//										partyTicketDetail.setLotteryTime(new Date());
//										partyTicketDetail.setTmmTicketCode(tmm_ticket_code);
//										partyTicketDetail.setTicketStatus(1);
//										partyTicketDetail.setUserId(user.getId());
//										partyTicketDetail.setUpdateDate(new Date());
//										partyTicketDetail.setPrizeDetailId(reward.getId());
//										partyTicketDetail.update();
//									}else{
//										easy.setMsg("您抽中的奖品已经发送完毕，请下次努力哦！");
//										easy.setSuccess(true);
//										return easy;
//									}
//								}
//							}
//						}else{
//							easy.setMsg("您抽中的奖品已经发送完毕，请下次努力哦！");
//							easy.setSuccess(true);
//							easy.setData(reward);
//							return easy;
//						}
//						
//						//奖励商品券
//						if(Db.update(MarketingSql.updateTicket(reward.getTicketId())) == 1){
//							//商品奖励信息汇总表
//							PartyPrizeSummary prizeSummary  ;
//							List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(reward.getId()));
//							if(prizeSummarieList.size() > 0){
//								prizeSummary  = prizeSummarieList.get(0);
//								prizeSummary.setPrizeNum(prizeSummary.getPrizeNum() + 1 );
//								prizeSummary.setUpdateDate(new Date());
//								prizeSummary.update();
//							}else{
//								prizeSummary = new PartyPrizeSummary();
//								prizeSummary.setPrizeNum(1);
//								prizeSummary.setPrizeId(reward.getId());
//								prizeSummary.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
//								prizeSummary.save();
//							}
//							//参与活动明细表
//							PartyPrizeRecord prizeRecord = new PartyPrizeRecord();
//							prizeRecord.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
//							prizeRecord.setPrizeId(reward.getId());
//							prizeRecord.setPrizeName(reward.getPrizeName());
//							prizeRecord.setUserId(user.getId());
//							prizeRecord.setParticipationTime(new Date());
//							prizeRecord.save();
//							
//							//确定抽奖
//							easy.setData(reward);
//							easy.setMsg("SUCCESS");
//							easy.setSuccess(true);
//						}else {
//							
//							easy.setMsg("您抽中的奖品已经发送完毕，请下次努力将哦！");
//							easy.setSuccess(true);
//						}
//					}else{
//						easy.setMsg("奖励已经发完，下次请早！");
//						easy.setSuccess(true);
//					}
//				}
//			}else{
//				easy.setMsg("您的抽奖次数已经用完了哦！");
//				easy.setSuccess(true);
//			}
//		}else{
//			easy.setMsg("您还没有获得抽奖次数！");
//			easy.setSuccess(true);
//		}
//		return easy;
	}

	/**
	 * @Description: 更新用户资源
	 * @param @param map
	 * @param @param rule   
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public Map<String, Object> updateLotteryNum(Map<String, Object> map,PartyRule rule){
		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		//这段时间内该用户获取的总的奖励次数
		PartyLotteryNum partyLotteryNum = null;
		int lotteryNum = 0;
		if(null!=map.get("LOGIN_NUM")&&""!=map.get("LOGIN_NUM")){
			//增加签到获取次数
			lotteryNum +=Integer.parseInt(map.get("LOGIN_NUM").toString()) * rule.getLoginNum();
		}
		if(null!=map.get("ORDER_NUM")&&""!=map.get("ORDER_NUM")){
			//增加下单获得次数
			lotteryNum +=Integer.parseInt(map.get("ORDER_NUM").toString())  * rule.getOrderNum();
		}
		if(null!=map.get("REPEAT_NUM")&&""!=map.get("REPEAT_NUM")){
			//增加转发获得次数
			lotteryNum +=Integer.parseInt(map.get("REPEAT_NUM").toString())  * rule.getRepeatNum();
		}

		List<PartyLotteryNum> lotteryNumList = lotteryNumDao.find(MarketingSql.getLotteryNum(map));
		//用户资源已经存在，则更新用户资源,否则新增一条用户资源
		if(lotteryNumList.size() > 0){
			partyLotteryNum = lotteryNumList.get(0);
			partyLotteryNum.setLotteryNum(lotteryNum + partyLotteryNum.getLotteryNum());
			partyLotteryNum.setUpdateDate(new Date());
			partyLotteryNum.update();
		}else{
			partyLotteryNum = new PartyLotteryNum();
			partyLotteryNum.setLotteryNum(lotteryNum);
			partyLotteryNum.setUserId((Integer)map.get("USER_ID"));
			partyLotteryNum.setPartyId((Integer)map.get("PARTY_ID"));
			partyLotteryNum.save();
		}
		resultMap.put("lotteryNum",lotteryNum );
		resultMap.put("partyLotteryNum",partyLotteryNum );
		return resultMap;
	}

	/**
	 * @Description:更新用户信息拉取表
	 * @param @param map   
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public void updateUserSerInfo(Map<String,Object> map) {
		List<PartyUserSerinfo> userSerinfoList = userSerinfoDao.find(MarketingSql.getUserSerInfo(map));
		PartyUserSerinfo userSerinfo = null;
		if(userSerinfoList.size() > 0){
			userSerinfo = userSerinfoList.get(0);
			userSerinfo.setUpdateDate(new Date());
			userSerinfo.setLastSerTime(new Date());
			userSerinfo.update();
		}else{
			userSerinfo = new PartyUserSerinfo();
			userSerinfo.setLastSerTime(new Date());
			userSerinfo.setUserId((Integer)map.get("USER_ID"));
			userSerinfo.setPartyId((Integer)map.get("PARTY_ID"));
			userSerinfo.save();
		}
	}



	/**
	 * @Description: 调用淘喵喵接口，判断奖品是否绑定成功
	 * @param @param user 用户信息
	 * @param @param ticket_code 淘喵喵券ID
	 * @param @return   
	 * @return String  淘喵喵券编码
	 * @throws
	 * @author liuxin
	 * @date 2018年6月4日
	 */
	public String getRewardFormTMM(PartyUser user,String ticket_id){
		String tmm_ticket_code = "";
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("coupon_id", ticket_id);
		paramMap.put("key",user.getRequestKey() );
		String urlString = xx.getConfig(user.getUserSource()+"URL" );
		System.out.println(xx.getConfig(user.getUserSource()+"URL" ));
		String result = HttpUtil.post(urlString+"api.php?controller=jackpot&action=sendCoupon", paramMap);
		System.out.println(result);
		JSONObject jb = JSON.parseObject(result);
		Map<String, Object> map = jb;
		//成功
		if(Integer.parseInt(map.get("errcode").toString())==0 ){
			Map<String, Object> ticketMap =(Map<String, Object>) map.get("info");
			tmm_ticket_code =  ticketMap.get("coupon_code").toString();
			System.out.println(tmm_ticket_code);
		}else{
			tmm_ticket_code = "ERR";
		}
		return tmm_ticket_code;

	}

}
